using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using MyCompany.MyProject.Common.Helper;
using MyCompany.MyProject.Common.UtilIity;
using MyCompany.MyProject.IService;
using MyCompany.MyProject.Model;
using MyCompany.MyProject.Model.DTO;
using MyCompany.MyProject.Model.Models;
using MyCompany.MyProject.WebApi.ModelDto.ModuleDto;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System.Text;

namespace MyCompany.MyProject.WebApi.Controllers;

/// <summary>
/// 接口管理
/// </summary>
public class ModuleController : BasePermissionApiController
{
    private readonly IBaseService<Modules> _moduleService;
    private readonly IMapper _mapper;
    private readonly IWebHostEnvironment _evn;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="moduleService"></param>
    /// <param name="mapper"></param>
    /// <param name="evn"></param>
    public ModuleController(IBaseService<Modules> moduleService, IMapper mapper, IWebHostEnvironment evn)
    {
        _moduleService = moduleService;
        _mapper = mapper;
        _evn = evn;
    }

    /// <summary>
    /// 获取接口列表
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<PageModel<ModulesVo>>> GetModules(int pageIndex = 1, int pageSize = 10, string key = "")
    {
        Expression<Func<Modules, bool>>? whereExpression = i => i.IsDeleted == false;
        if (!string.IsNullOrEmpty(key))
        {
            whereExpression = whereExpression.And(i => i.Name.Contains(key) || i.Code.Contains(key) || i.Controller.Contains(key) || i.Action.Contains(key));
        }
        PageModel<ModulesVo> data = new PageModel<ModulesVo>();
        if (pageIndex == -1)
        {
            data.Data =_mapper.Map<List<ModulesVo>>( await _moduleService.Query(whereExpression));
        }
        else
        {
            var res = await _moduleService.QueryPage(whereExpression, pageIndex, pageSize, "Id desc");
            data = res.ConvertTo<ModulesVo>(_mapper);
        }
        return Success(data);
    }

    /// <summary>
    /// 新增接口
    /// </summary>
    /// <param name="modulesVo"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<MessageModel<string>> Post(ModulesVo modulesVo)
    {
        //var modules = _mapper.Map<Modules>(modulesVo);
        var res = await _moduleService.Add(_mapper.Map<Modules>(modulesVo));
        return Success(res.ToString(), "操作成功");
    }

    /// <summary>
    /// 更新接口
    /// </summary>
    /// <param name="modulesVo"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<MessageModel<string>> Put(ModulesVo modulesVo)
    {
        var res = await _moduleService.Update(_mapper.Map<Modules>( modulesVo));
        return Success(res.ToString(), "操作成功");
    }
    /// <summary>
    /// 删除接口
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<MessageModel<string>> Delete(long id)
    {
        var modules = await _moduleService.QueryById(id);
        modules.IsDeleted = true;
        var res = await _moduleService.Update((modules));
        return Success(res.ToString(), "操作成功");
    }

    /// <summary>
    /// 根据数据生成TSV文件，仅开发环境可用
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<string>> SaveDataToTsv()
    {
        var data = new MessageModel<string>();
        if (_evn.IsDevelopment())
        {
            JsonSerializerSettings jsonSerializer = new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            var Modules = await _moduleService.Query();
            var json = JsonConvert.SerializeObject(Modules, jsonSerializer);
            FileHelper.WriteFile(Path.Combine(_evn.WebRootPath,"SeedData", "Modules.tsv"),json,Encoding.UTF8);
            data.success = true;
            data.msg = "操作成功";
        }
        else
        {
            data.success = false;
            data.msg = "仅开发环境可用";
        }

        return data;
    }
}
